<?php
/**
 * Created by PhpStorm.
 * User: czw
 * Date: 2018/7/11
 * Time: 14:59
 */
namespace app\common\model;

use app\admin\validate\IDMustBePositiveInt;
use app\lib\exception\BaseException;
use app\lib\exception\CreateException;
use app\lib\exception\DeleteException;
use app\lib\exception\NotFoundException;
use app\lib\exception\UpdateException;

class Role extends BaseModel
{
    protected $hidden = ['pivot','delete_time'];
    public function permission(){
        return $this->hasMany('Permission');
    }
    public static function getAll(){
        return self::select();
    }
    public static function createOne($data){
        $model = new self();
        $role = $model->where(['name' => $data['name']])->find();
        if ($role) throw new BaseException(['msg' => '角色已存在！']);
        $res = $model->allowField(true)->save($data);
    }
    public static function updateOne($id,$data){
        (new IDMustBePositiveInt())->check($id);
        $res = (new self())->allowField(true)->where('id='.$id)->update($data);
        if(!$res){
            throw (new UpdateException());
        }
    }
    public function getRolesById($id){
        (new IDMustBePositiveInt())->check($id);
        return self::where('id='.$id)->select();
    }
    public static function deleteOne($id){
        $role = self::get($id);
        if(!$role) throw (new NotFoundException());
        $res = self::destroy($id);
        if(!$res) throw (new DeleteException());
    }
}